//
//  AppDelegate.m
//  Text_ problem
//
//  Created by jiboxue on 13-1-7.
//  Copyright (c) 2013年 jiboxue. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "PMAPI.h"
#import "JSON.h"
#import "CustomerInformation.h"
#import "Reachability.h"


#import "EnvelopeAnimationViewController.h"

@interface AppDelegate ()

@property (nonatomic, retain) ASIHTTPRequest *request;

@end

@implementation AppDelegate

@synthesize rootVC;

- (void)dealloc
{
    [self.request clearDelegatesAndCancel];
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //self.envelopeVC = [[[EnvelopeAnimationViewController alloc]init]autorelease];
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    rootVC = [[[RootViewController alloc]initWithNibName:@"RootViewController" bundle:nil]autorelease];
    [[UIApplication sharedApplication]setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    self.window.rootViewController = rootVC;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(login) withObject:nil afterDelay:0];
    
    [self registerPushNotifcation];
    
    NSDictionary *userInfoDic = [CustomerInformation userMessage];
    NSString *deviceTokenString =  [[NSUserDefaults standardUserDefaults] stringForKey:@"deviceTokenString"];
    
    if (userInfoDic != nil && [deviceTokenString length] > 0) {
        
        NSString *username = [userInfoDic objectForKey:@"username"];
        NSString *password = [userInfoDic objectForKey:@"password"];
        
        ASIHTTPRequest *tokenRequest =
        [PMAPI registerNotification:deviceTokenString
                        andUsername:username
                        andPassword:password];
        self.request = tokenRequest;
        
        [tokenRequest startAsynchronous];
    }

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    //程序会发到前台的时候调用
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
//    [self home];
//    NSLog(@"buzhidaoshenmshihou");
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    //    self.rootVC = rootVC = [[[RootViewController alloc]initWithNibName:@"RootViewController" bundle:nil]autorelease];
    //    self.window.rootViewController = rootVC;
    //程序恢复到前台是调用
    //[self performSelector:@selector(home) withObject:nil afterDelay:0];
    
    //    [self performSelector:@selector(home) withObject:nil afterDelay:0];
    //[NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self home];
    NSLog(@"home");
    //程序推出到后台是调用(响应home键)
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if (![self isOnline])
    {
        [self.rootVC addLandingViewController];
        [self.rootVC showLandingWifi];
    }
    else
    {
        if ([self checkUsernameAndPassword]) {
            
        }
    }
  
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    //程序终止(相应短信或电话是调用)(保存数据)
    
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
}
- (BOOL)isOnline
{
    
    BOOL isExistenceNetwork = YES;
    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork=NO;
            //   NSLog(@"没有网络");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork=YES;
            //   NSLog(@"正在使用3G网络");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork=YES;
            //  NSLog(@"正在使用wifi网络");
            break;
    }
    return isExistenceNetwork;
}
- (BOOL)checkUsernameAndPassword
{
    NSLog(@"4444");
    BOOL result = NO;
    NSDictionary *dictionaryUserInfo = [CustomerInformation userMessage];
    NSLog(@"sdsadasdsad%@",dictionaryUserInfo);
    if (dictionaryUserInfo) {
        NSLog(@"555");
        NSString *username = [dictionaryUserInfo objectForKey:@"username"];
        //这个没有
        NSString *password = [dictionaryUserInfo objectForKey:@"password"];
        NSLog(@"username%@",username);
        NSLog(@"password%@",password);
        ASIHTTPRequest *request = [PMAPI requestLoginUsername:username andPassword:password];
        [request startSynchronous];
        
        if ([request responseStatusCode] == 401) {
            [CustomerInformation clear];
            return NO;
        }
        //        else if ([request error]) {
        //            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //            [alertView show];
        //            [alertView release];
        //
        //            return NO;
        //        }
        else
        {
            NSMutableDictionary *userInfo = [request.responseString JSONValue];
            [userInfo setObject:password forKey:@"password"];
            [CustomerInformation save:userInfo];
            [self.rootVC removeview];
            
            return YES;
        }
    }
    
    return result;
}

- (void)login
{
    [self.rootVC showLandingViewController];
    if ([self isOnline])
    {
        NSLog(@"333");
        if ([self checkUsernameAndPassword])
        {
            [self.rootVC removeview];
            //            [self.rootVC closeAll];
        }
    }
    else{
        [self.rootVC showLandingWifi];
    }
}

- (void)registerPushNotifcation
{
    [[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     | UIRemoteNotificationTypeSound
     | UIRemoteNotificationTypeAlert];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSString *str = [NSString stringWithFormat: @"Error: %@", err];
    NSLog(@"Error:%@",str);
}

//register from app server to get token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    const unsigned *tokenBytes = [deviceToken bytes];
    NSString* deviceTokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                   ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                   ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                   ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    
    NSLog(@"%@", deviceTokenString);
    [[NSUserDefaults standardUserDefaults] setValue:deviceTokenString forKey:@"deviceTokenString"];
    
}

//receive notification from app server
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    for (id key in userInfo) {
        NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
    }
    
    [self.rootVC timerinvalidate];
    
    [[NSNotificationCenter defaultCenter]
     postNotificationName:USERDEFAULT_WRITEOK object:nil];
}
-(void)home
{
    //[self.envelopeVC stopTimers];
    //[self.envelopeVC back];
    
    //self.envelopeVC = [[[EnvelopeAnimationViewController alloc]init]autorelease];
//    [self.envelopeVC.view removeFromSuperview];
    [self.rootVC.EnvelopeAnimationVC stopTimers];
    [self.rootVC.EnvelopeAnimationVC back];
    
    //[self.rootVC.EnvelopeAnimationVC.view removeFromSuperview];
    //self.rootVC.EnvelopeAnimationVC = [[[EnvelopeAnimationViewController alloc] init]autorelease];
    
    [self.rootVC timerinvalidate];
}

@end
